package Vocabulary;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MybatisUtils {
    static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            //使用Mybatis第一步：获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("110");
        }
    }

    //既然有了SqlSessionFactory，顾名思义，我们需要获得SqlSession的实例
    //SqlSession 提供了在数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

    public static void main(String[] args) {
        System.out.println("结果："+getSqlSession());
    }
    public static byte[] serialize(List<List<byte[]>> object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }
    public static List<List<byte[]>> deserialize(byte[] data) throws IOException, ClassNotFoundException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        return (List<List<byte[]>>) objectInputStream.readObject();
    }
    public static byte[] convertListToByteArray(List<byte[]> byteList) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (byte[] bytes : byteList) {
            outputStream.write(bytes);
        }
        return outputStream.toByteArray();
    }

    public static List<byte[]> convertByteArrayToList(byte[] byteArray, int arraySize) {
        List<byte[]> resultList = new ArrayList<>();
        for (int i = 0; i < byteArray.length; i += arraySize) {
            byte[] subArray = new byte[arraySize];
            System.arraycopy(byteArray, i, subArray, 0, arraySize);
            resultList.add(subArray);
        }
        return resultList;
    }
}

